#!/usr/bin/python
# -*- coding: utf-8 -*-
# File: icons.py
# Author: Tomás Vírseda
# License: GPL v3
# Description: Icon manager for Vazaar

import os
import os.path
import subprocess

import md5

import gobject
import gtk

from vazaarlib.constants import IMAGES_DIR, VAZAAR_USER_THUMBS_DIR
from vazaarlib.utils import get_logger
from vazaarlib.namespaces import *

WIDTH = 48
HEIGHT = 48



class IconManager():
    def __init__(self, gui):
        self.gui = gui
        self.app = gui.app
        self.gui.settings['icons'] = {}
        self.gui.settings['icons']['default_size'] = 48
        self.iconset = {}
        self.get_settings()
        self.setup_basic_icons(WIDTH,  HEIGHT)

    def add_icon(self, name, width=WIDTH, height=HEIGHT, ):
        key = name + '-' + str(width) + 'x' + str(height)
        #print "add_icon", key
        try:
            assert(self.iconset[key])
        except:
            try:
                self.iconset[key] = gtk.gdk.pixbuf_new_from_file_at_size(IMAGES_DIR + "/" + name, int(width), int(height))
            except:
                self.setup_basic_icons(width, height)
                self.get_icon_by_name(name, width, height)



    def setup_basic_icons(self, width=WIDTH, height=HEIGHT):
        partkey = '-' + str(width) + 'x' + str(height)
        self.iconset[PIMO['Collection']+partkey] = gtk.gdk.pixbuf_new_from_file_at_size(IMAGES_DIR+"/Collection.svg", width, height)
        self.iconset[NFO['Application']+partkey] = gtk.gdk.pixbuf_new_from_file_at_size(IMAGES_DIR+"/Application.svg", width, height)
        self.iconset[NFO['Resource']+partkey] = gtk.gdk.pixbuf_new_from_file_at_size(IMAGES_DIR+"/opml.svg", width, height)
        self.iconset[NFO['Clipboard']+partkey] = gtk.gdk.pixbuf_new_from_file_at_size(IMAGES_DIR+"/Clipboard.svg", width, height)
        self.iconset[NFO['Image']+partkey] = gtk.gdk.pixbuf_new_from_file_at_size(IMAGES_DIR+"/Image.svg", width, height)
        self.iconset[NFO['Audio']+partkey] = gtk.gdk.pixbuf_new_from_file_at_size(IMAGES_DIR+"/Collection.svg", width, height)
        self.iconset[NFO['Website']+partkey] = gtk.gdk.pixbuf_new_from_file_at_size(IMAGES_DIR+"/Website.svg", width, height)
        self.iconset[NFO['TextDocument']+partkey] = gtk.gdk.pixbuf_new_from_file_at_size(IMAGES_DIR+"/TextDocument.svg", width, height)
        self.iconset[NFO['Folder']+partkey] = gtk.gdk.pixbuf_new_from_file_at_size(IMAGES_DIR+"/Folder.svg", width, height)
        self.iconset[NFO['Feed']+partkey] = gtk.gdk.pixbuf_new_from_file_at_size(IMAGES_DIR+"/Feed.svg", width, height)
        self.iconset[NFO['RemoteDataObject']+partkey] = gtk.gdk.pixbuf_new_from_file_at_size(IMAGES_DIR+"/RemoteDataObject.svg", width, height)
        self.iconset[NFO['Audio']+partkey] = gtk.gdk.pixbuf_new_from_file_at_size(IMAGES_DIR+"/Audio.svg", width, height)
        self.iconset[NFO['Video']+partkey] = gtk.gdk.pixbuf_new_from_file_at_size(IMAGES_DIR+"/Video.svg", width, height)
        self.iconset[NFO['Desktop']+partkey] = gtk.gdk.pixbuf_new_from_file_at_size(IMAGES_DIR+"/Desktop.svg", width, height)
        self.iconset[NFO['Unknow']+partkey] = gtk.gdk.pixbuf_new_from_file_at_size(IMAGES_DIR+"/Unknown.svg", width, height)
        #print self.iconset

    def get_icon_by_mime(self, mimetype, width, height):
        self.cache = {}
        media = mimetype[0:mimetype.find('/')]
        detail = mimetype[mimetype.find('/') + 1:]
        #get mime type
        mime_type = gnomevfs.get_mime_type( path ).replace( '/', '-' )
        try:
            if media == 'collection':
                return self.get_icon_by_name(PIMO['Collection'], width, height)
            elif media == 'text':
                return self.get_icon_by_name(NFO['TextDocument'], width, height)
            elif media == 'image':
                return self.get_icon_by_name(NFO['Image'], width, height)
            elif media == 'application':
                return self.get_icon_by_name(NFO['Application'], width, height)
            elif media == 'audio':
                return self.get_icon_by_name(NFO['Audio'], width, height)
            elif media == 'inode':
                return self.get_icon_by_name(NFO['Folder'], width, height)
            elif media == 'video':
                return self.get_icon_by_name(NFO['Video'], width, height)
            else:
                return self.get_icon_by_name(NFO['Unknow'], width, height)
        except:
            return None

    def get_icon_by_name(self, name, width=WIDTH, height=HEIGHT):
        key = name + '-' + str(width) + 'x' + str(height)
        #print "get_icon_by_name", key
        try:
            return self.iconset[key]
        except:
            self.add_icon(name, width, height)
            return self.iconset[key]


    def get_icon_from_path(self, uri, path, size):
        return None
        try:
            thumbnailer = '/usr/bin/evince-thumbnailer'
            thesize = "--size=48"
            print uri, path, size
            subprocess.call ([thumbnailer, thesize, uri, path])
            return gtk.gdk.pixbuf_new_from_file(path)

        except Exception, error:
            print error
            return None

    def thumbnail_path_from_uri(self, uri, size='normal'):
        """Construct the path for the thumbnail of the given uri

        Arguments:
        - `uri`: the uri that points to the file that is looking for the thumbnail.
        - `size`: the size of the thumbnail (normal or large)
        http://freyes.blogspot.com/2008/07/get-thumbnail-of-file-with-python.html
        """

        assert isinstance(uri, basestring), \
               TypeError("The uri must be a str")

        assert isinstance(size, basestring) and (size == 'large' or size=='normal'), \
               TypeError("The size for thumbnail can be normal or large")

        hash = md5.new()
        hash.update(uri)
        path = os.path.join(VAZAAR_USER_THUMBS_DIR, size, str("%s.png" % hash.hexdigest()))

        return path


    def get_settings(self):
        try:
            self.gui.settings['icons']['default_size'] = self.app.cfgmgr.get_value('Icons', 'default_size')
        except Exception, error:
            self.save_default_settings()


    def save_default_settings(self):
        try:
            self.app.cfgmgr.set_value('Icons', 'default_size', self.gui.settings['icons']['default_size'])
            self.app.cfgmgr.write_config()
        except Exception, error:
            print error #pass #self.log.error("save:: %s" % error)
